package com.example.accessibilitydemo.service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.example.accessibilitydemo.util.PreferenceUtil;

/**
 * 微信统计好友数量
 * 
 * @author chencq
 *
 */
public class WeChatFriendCountService extends BaseAccessibilityService {

	private static final String TAG = WeChatFriendCountService.class.getSimpleName();

	private static boolean fcount = false;

	private List<AccessibilityNodeInfo> target = null;
	private int friendCount = 0;

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		super.onAccessibilityEvent(event);
		try {
			fcount = PreferenceUtil.getBoolean("fcount", false);
			int eventType = event.getEventType();

			if (!fcount)
				return;

			if (eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
					&& event.getClassName().equals("com.tencent.mm.ui.LauncherUI")) {
				// 通讯录
				AccessibilityNodeInfo contactTab = findView("com.tencent.mm:id/bq0", "通讯录");
				performViewClick(contactTab);
				sleep(1000);

				friendCount = getFriendCount();

				Log.i(TAG, "好友数量:" + friendCount);
			}
		} catch (Exception e) {
			Log.i(TAG, "throw exception:" + e);
		} finally {
			PreferenceUtil.commitBoolean("fcount", false);
		}
	}

	public int getFriendCount() {
		AccessibilityNodeInfo rootNode = getRootInActiveWindow();
		target = rootNode.findAccessibilityNodeInfosByText("位联系人");
		int count = 0;
		while (target == null || target.isEmpty()) {
			for (int k = 0; k < rootNode.getChild(0).getChildCount(); k++) {
				if (rootNode.getChild(0).getChild(k).getClassName().equals("android.widget.ListView")) {
					AccessibilityNodeInfo node_lsv = rootNode.getChild(0).getChild(k);
					node_lsv.performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
					Log.i(TAG, "向上滑动.......");
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								Thread.sleep(1000);
							} catch (InterruptedException mE) {
								mE.printStackTrace();
							}

							AccessibilityNodeInfo rootNode_ = getRootInActiveWindow();
							target = rootNode_.findAccessibilityNodeInfosByText("位联系人");
						}
					}).start();
				}
			}
		}

		return getNumbers(target.get(0).getText().toString());
	}

	// 截取数字
	public int getNumbers(String content) {
		if (!"".equals(content)) {
			Pattern pattern = Pattern.compile("\\d+");
			Matcher matcher = pattern.matcher(content);
			while (matcher.find()) {
				return Integer.parseInt(matcher.group(0));
			}
		}
		return 0;
	}
}
